package action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import entity.Choose;
import entity.Question;
import entity.Survey;
import service.QuestionService;

@Controller

public class QuestionAction {
	@Autowired

	private QuestionService questionService;

	public QuestionService getQuestionService() {
		return questionService;
	}

	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}

	@RequestMapping("/addQuestion.do")
	public ModelAndView addQuestion(String surveyTitle, Integer[] questionId, String[] title, Integer surveyId,
			String[] content, Integer[] nums, Integer[] questionType) {

		List<Question> questionList = new ArrayList<Question>();

		Survey survey = new Survey();

		survey.setSurveyId(surveyId);

		survey.setSurveyTitle(surveyTitle);

		for (int i = 0; i < title.length; i++) {
			Question question = new Question();
			question.setQuestionId(questionId[i]);
			question.setSurveyId(surveyId);
			question.setTitle(title[i]);
			question.setQuestionType(questionType[i]);
			questionList.add(question);
		}

		boolean suSuc = false;
		for (int i = 0; i < title.length; i++) {
			suSuc = questionService.addQuestion(questionList.get(i));
		}
		boolean quSuc = questionService.addSurvey(survey);

		List<Choose> chooseList = new ArrayList<Choose>();

		for (int i = 0; i < questionId.length; i++) {

			Question quQuesId = null;

			quQuesId = questionService.queryQuestionId(questionList.get(i));
			for (int j = 0; j < nums[i]; j++) {
				Choose choose = new Choose();
				// System.out.println(j);
				int preNum;
				if (i == 0) {
					preNum = 0;
				} else {
					preNum = nums[i - 1];
				}
				choose.setQuestionId(quQuesId.getQuestionId());
				choose.setContent(content[preNum + j]);

				chooseList.add(choose);
			}
		}
		boolean opSuc = false;
		for (int i = 0; i < chooseList.size(); i++) {
			opSuc = questionService.addChoose(chooseList.get(i));
		}
		Map<String, Object> model = new HashMap<String, Object>();
		if (quSuc && suSuc && opSuc) {
			model.put("questionTitle", surveyTitle);
			return new ModelAndView("Survey", model);
		} else {
			model.put("info", "添加失败");
			return new ModelAndView("Survey", model);
		}
	}

}
